package app;

import app.models.OperLog;
import com.google.common.base.Strings;
import com.jfinal.core.Controller;
import goja.rapid.syslog.LogConfig;
import goja.rapid.syslog.LogProcessor;
import goja.rapid.syslog.SysLog;
import goja.security.shiro.AppUser;
import goja.security.shiro.Securitys;
import org.joda.time.DateTime;

import java.util.Map;
import java.util.Set;

/**
 * <p>
 * <p/>
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class SystemLogProcessor implements LogProcessor {
    @Override
    public void process(SysLog sysLog) {
        OperLog operLog = new OperLog();
        operLog.set("module_name", sysLog.getTitle());
        operLog.set("content", sysLog.getMessage());
        operLog.set("record_time", DateTime.now().toDate());
        operLog.set("operator", Securitys.getLogin().id);
        operLog.set("operator_name", sysLog.getUser());
        operLog.save();
    }

    @Override
    public String getUsername(Controller c) {
        AppUser user = Securitys.getLogin();
        if (user != null) {
            return user.name;
        }
        return null;
    }

    @Override
    public String formatMessage(LogConfig config, Map<String, String> message) {
        boolean isFormat = Strings.isNullOrEmpty(config.getTitle());
        String result = isFormat ? config.getFormat() : config.getTitle();
        if (message.isEmpty()) {
            return result;
        }
        if (isFormat) {
            Set<Map.Entry<String, String>> entrySet = message.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                String key = entry.getKey();
                String value = entry.getValue();
                result = result.replace("{" + key + "}", value);
            }
        } else {
            result += ", ";
            Set<Map.Entry<String, String>> entrySet = message.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                String key = entry.getKey();
                String value = entry.getValue();
                result += key + ":" + value;
            }
        }
        return result;
    }
}
